package com.compass.mobile.ui.activity

import UserInfoManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import com.compass.mobile.R
import com.compass.mobile.databinding.ActivityHealthRecordBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.HEALTH
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.constant.YY_NURSING
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.ChartUtils
import com.compass.mobile.framework.utils.CodeUtils.getCodeUrl
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.MyValueFormatter
import com.compass.mobile.models.HealthBean
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.viewModel.HealthRecordViewModel
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import getColorFromResource

/**
 * Description： 健康档案
 * Date:2024/6/20 10:30
 */
class HealthRecordActivity : BaseVBActivity<ActivityHealthRecordBinding>() {
    private val colors = intArrayOf(
        Color.rgb(92, 141, 242),
        Color.rgb(246, 139, 17),
        Color.rgb(249, 224, 195),
        Color.rgb(255, 97, 138),
        Color.rgb(255, 255, 255),
        Color.rgb(239, 82, 46)
    )
    private val healthRecordViewModel: HealthRecordViewModel by viewModels()
    private var weekList: MutableList<HealthBean> = mutableListOf()//本周数据
    private var age: String? = null
    private var gender: String? = null

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, HealthRecordActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        UserInfoManager.getPatientInfo()?.let {
            age = DateUtils.formatAgeToNumber(UserInfoManager.getPatientInfo()?.birthday)
            gender = UserInfoManager.getPatientInfo()?.sex
        }
    }

    override fun initData() {
        ChartUtils.initLineChart(mBinding.lineChart)
        healthRecordViewModel.getHealthy(UserInfoManager.getPatientInfo()?.id)
        healthRecordViewModel.healthLiveData.observe(this) {
            it?.let {
                weekList = it.weekList
                it.physicalFitnessTest?.let { physical ->
                    mBinding.tvWeight.text = physical.weight
                    mBinding.tvHeight.text = physical.height
                }
                it.totalAvg?.let { total ->
                    mBinding.tvHeightPressure.text = total.getHighPressure()
                    mBinding.tvLowPressure.text = total.getLowPressure()
                    mBinding.tvAvgBloodGlucose.text = total.getBloodGlucose()
                    mBinding.tvAvgUricAcid.text = total.getUricAcid()
                }

                healthRecordViewModel.healthAssessment(
                    age,
                    gender,
                    it.physicalFitnessTest?.height,
                    it.physicalFitnessTest?.weight,
                    it.totalAvg?.avgBloodGlucose,
                    it.totalAvg?.avgHighPressure,
                    it.totalAvg?.avgLowPressure,
                    it.totalAvg?.avgUricAcid
                )
                mBinding.llLowPressure.requestFocus()

            }
        }
        healthRecordViewModel.assessmentLiveData.observe(this) {
            it?.let {
                mBinding.tvHealthAssessment.text = it.content
            }?:kotlin.run {
                mBinding.tvHealthAssessment.text = "数据不全，暂时无法进行健康评估"
            }
        }


    }

    override fun intListener() {
        mBinding.tvAdd.onClick {
            openEdit()
        }

        mBinding.llLowPressure.setOnFocusChangeListener { view, b ->

            if (b) {

                mBinding.tvHeightPressureKey.setTextColor(getColorFromResource(R.color.white))
                mBinding.tvHeightPressure.setTextColor(getColorFromResource(R.color.white))
                mBinding.tvtvLowPressureKey.setTextColor(getColorFromResource(R.color.white))
                mBinding.tvLowPressure.setTextColor(getColorFromResource(R.color.white))
                setPressureData()
            } else {
                mBinding.tvHeightPressureKey.setTextColor(getColorFromResource(R.color.main_title))
                mBinding.tvtvLowPressureKey.setTextColor(getColorFromResource(R.color.main_title))
                mBinding.tvHeightPressure.setTextColor(getColorFromResource(R.color.blue_title))
                mBinding.tvLowPressure.setTextColor(getColorFromResource(R.color.blue_title))
            }
        }

        mBinding.llBloodGlucose.setOnFocusChangeListener { view, b ->

            if (b) {
                mBinding.tvAvgBloodGlucose.setTextColor(getColorFromResource(R.color.white))
                setBloodGlucoseData()
            } else {
                mBinding.tvAvgBloodGlucose.setTextColor(getColorFromResource(R.color.blue_title))
            }
        }

        mBinding.llUricAcid.setOnFocusChangeListener { view, b ->

            if (b) {
                mBinding.tvAvgUricAcid.setTextColor(getColorFromResource(R.color.white))
                setUricAcidData()
            } else {
                mBinding.tvAvgUricAcid.setTextColor(getColorFromResource(R.color.blue_title))
            }
        }

    }

    private fun openEdit() {
        val url = "$HEALTH${getCodeUrl()}"
        val oderCodeDialog = CodeDialog.Builder(this, url)
        oderCodeDialog.show()
    }

    private val animateTime = 1000

    /**
     * 设置血压数据
     */
    private fun setPressureData() {
        mBinding.lineChart.animateY(animateTime, Easing.EaseInOutQuad)

        if (weekList.isEmpty()) {
            return
        }
        val valuesLow = ArrayList<Entry>()
        val valuesHigh = ArrayList<Entry>()

        var maxNumber = 0.0f
        var countLow: Float
        var countHigh: Float

        for (i in weekList.indices) {
            countLow = weekList[i].getLowPressure().toFloat()
            countHigh = weekList[i].getHighPressure().toFloat()

            if (maxNumber < countLow) {
                maxNumber = countLow
            }
            if (maxNumber < countHigh) {
                maxNumber = countHigh
            }


            valuesLow.add(Entry(i.toFloat(), countLow))
            valuesHigh.add(Entry(i.toFloat(), countHigh))

        }
        mBinding.lineChart.legend.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.setNoDataText("暂无数据")
        //设置Y左边轴显示的值 label 数量
        mBinding.lineChart.axisLeft.setLabelCount(weekList.size, true)
        //设置x轴最大显示数量
        mBinding.lineChart.xAxis.setLabelCount(weekList.size, true)
        //设置Y轴最大值比集合最大值大5
        mBinding.lineChart.axisLeft.axisMaximum = (maxNumber + 10)
        mBinding.lineChart.axisLeft.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.xAxis.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.xAxis.valueFormatter = (object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                var position = value.toInt()
                return DateUtils.conversionTime(
                    weekList[position].measurementDate,
                    DateUtils.FORMAT_FIVE
                )
            }
        })
        val setLow = LineDataSet(valuesLow, "低压")
        setLow.setDrawIcons(false)
        setLow.mode = LineDataSet.Mode.CUBIC_BEZIER
        setLow.lineWidth = 1.75f
        setLow.circleRadius = 5f
        setLow.circleHoleRadius = 2.5f
        setLow.color = colors[0]
        setLow.setCircleColor(colors[0])
        setLow.highLightColor = colors[0]
        setLow.setDrawCircleHole(true)
        setLow.valueTextSize = 12f
        setLow.valueTextColor = getColorFromResource(R.color.white)


        val setHigh = LineDataSet(valuesHigh, "高压")
        setHigh.setDrawIcons(false)
        setHigh.mode = LineDataSet.Mode.CUBIC_BEZIER
        setHigh.lineWidth = 1.75f
        setHigh.circleRadius = 5f
        setHigh.circleHoleRadius = 2.5f
        setHigh.color = colors[1]
        setHigh.setCircleColor(colors[1])
        setHigh.highLightColor = colors[1]
        setHigh.setDrawCircleHole(true)
        setHigh.valueTextSize = 12f
        setHigh.valueTextColor = getColorFromResource(R.color.white)

        val dataSets = ArrayList<ILineDataSet>()
        dataSets.add(setLow)
        dataSets.add(setHigh)
        val data = LineData(dataSets)
        data.setValueFormatter(MyValueFormatter())
        mBinding.lineChart.data = data
    }


    /**
     * 设置血糖数据
     */
    private fun setBloodGlucoseData() {
        mBinding.lineChart.animateY(animateTime, Easing.EaseInOutQuad)

        if (weekList.isEmpty()) {
            return
        }
        val valuesLow = ArrayList<Entry>()


        var maxNumber = 0.0f
        var countBlood: Float


        for (i in weekList.indices) {
            countBlood = weekList[i].getBloodGlucose().toFloat()


            if (maxNumber < countBlood) {
                maxNumber = countBlood
            }

            valuesLow.add(Entry(i.toFloat(), countBlood))

        }
        mBinding.lineChart.legend.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.setNoDataText("暂无数据")
        //设置Y左边轴显示的值 label 数量
        mBinding.lineChart.axisLeft.setLabelCount(weekList.size, true)
        //设置x轴最大显示数量
        mBinding.lineChart.xAxis.setLabelCount(weekList.size, true)
        //设置Y轴最大值比集合最大值大5
        mBinding.lineChart.axisLeft.axisMaximum = (maxNumber + 10)
        mBinding.lineChart.axisLeft.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.xAxis.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.xAxis.valueFormatter = (object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                var position = value.toInt()
                return DateUtils.conversionTime(
                    weekList[position].measurementDate,
                    DateUtils.FORMAT_FIVE
                )
            }
        })
        val setLow = LineDataSet(valuesLow, "血糖")
        setLow.setDrawIcons(false)
        setLow.mode = LineDataSet.Mode.CUBIC_BEZIER

        setLow.lineWidth = 1.75f
        setLow.circleRadius = 5f
        setLow.circleHoleRadius = 2.5f
        setLow.color = colors[0]
        setLow.setCircleColor(colors[0])
        setLow.highLightColor = colors[0]
        setLow.setDrawCircleHole(true)
        setLow.valueTextSize = 12f
        setLow.valueTextColor = getColorFromResource(R.color.white)

        val dataSets = ArrayList<ILineDataSet>()
        dataSets.add(setLow)
        val data = LineData(dataSets)
        data.setValueFormatter(MyValueFormatter())
        mBinding.lineChart.data = data
    }


    /**
     * 设置尿酸数据
     */
    private fun setUricAcidData() {
        mBinding.lineChart.animateY(animateTime, Easing.EaseInOutQuad)

        if (weekList.isEmpty()) {
            return
        }
        val valuesLow = ArrayList<Entry>()


        var maxNumber = 0.0f
        var countBlood: Float


        for (i in weekList.indices) {
            countBlood = weekList[i].getUricAcid().toFloat()


            if (maxNumber < countBlood) {
                maxNumber = countBlood
            }

            valuesLow.add(Entry(i.toFloat(), countBlood))

        }
        mBinding.lineChart.setNoDataText("暂无数据")
        //设置Y左边轴显示的值 label 数量
        mBinding.lineChart.axisLeft.setLabelCount(weekList.size, true)
        //设置x轴最大显示数量
        mBinding.lineChart.xAxis.setLabelCount(weekList.size, true)
        //设置Y轴最大值比集合最大值大5
        mBinding.lineChart.axisLeft.axisMaximum = (maxNumber + 10)
        mBinding.lineChart.axisLeft.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.xAxis.textColor = getColorFromResource(R.color.white)
        mBinding.lineChart.xAxis.valueFormatter = (object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                var position = value.toInt()
                return DateUtils.conversionTime(
                    weekList[position].measurementDate,
                    DateUtils.FORMAT_FIVE
                )
            }
        })
        mBinding.lineChart.legend.textColor = getColorFromResource(R.color.white)
        val setLow = LineDataSet(valuesLow, "尿酸")
        setLow.setDrawIcons(false)
        setLow.mode = LineDataSet.Mode.CUBIC_BEZIER
        setLow.lineWidth = 1.75f
        setLow.circleRadius = 5f
        setLow.circleHoleRadius = 2.5f
        setLow.color = colors[0]
        setLow.setCircleColor(colors[0])
        setLow.highLightColor = colors[0]
        setLow.setDrawCircleHole(true)
        setLow.valueTextSize = 12f
        setLow.valueTextColor = getColorFromResource(R.color.white)

        val dataSets = ArrayList<ILineDataSet>()
        dataSets.add(setLow)
        val data = LineData(dataSets)
        data.setValueFormatter(MyValueFormatter())
        mBinding.lineChart.data = data
    }
}